package adfc2.tasks;

import adfc2.actions.ReactionAction;
import adfc2.core.*;
import adfc2.entities.DroppedItem;
import adfc2.entities.Workshop;

// TODO if workshop == null
public class ReactionTask extends Task {

    public final Reaction reaction;
    private ReactionAction reactionAction;
    private int itemIndex = 0;
    private EnterWorkshopTask enterWorkshopSubtask;
    private PutTask putSubtask;
    private PickupTask pickupSubtask;
    private TakeTask takeSubtask;


    public ReactionTask(Creature actor, Reaction reaction) {
        super(actor);
        this.reaction = reaction;
    }

    @Override
    public Action nextAction() {
        if (reactionAction != null && reactionAction.completed) {
            completed();
            return null;
        } else if (itemIndex == reaction.input.length) {
            if (actor.container == reaction.workshop) {
                reactionAction = new ReactionAction(actor, reaction);
                return reactionAction;
            } else {
                if (enterWorkshopSubtask == null) {
                    enterWorkshopSubtask = new EnterWorkshopTask(actor, reaction.workshop);
                }
                return enterWorkshopSubtask.nextAction();
            }
        } else {
            Item item = reaction.input[itemIndex];
            if (item.owner == reaction.workshop) {
                itemIndex++;
                return nextAction();
            } else if (item.owner == actor) {
                if (putSubtask == null || putSubtask.completed) {
                    putSubtask = new PutTask(actor, item, reaction.workshop);
                }
                return putSubtask.nextAction();
            } else {
                if (item.owner instanceof DroppedItem) {
                    if (pickupSubtask == null || pickupSubtask.completed) {
                        pickupSubtask = new PickupTask(actor, (DroppedItem) item.owner);
                    }
                    return pickupSubtask.nextAction();
                } else if (item.owner instanceof Workshop) {
                    if (takeSubtask == null || takeSubtask.completed) {
                        takeSubtask = new TakeTask(actor, item);
                    }
                    return takeSubtask.nextAction();
                } else {
                    failed();
                    return null;
                }
            }
        }
    }

    @Override
    public String shortName() {
        return reaction.shortName();
    }
}
